﻿declare var angular: any;
declare var noty: Function;

angular.element().ready(() => {
    var app: any = angular.module("app", ['ngSanitize', 'ngRoute', 'textAngular', 'ui.select']);
    'use strict';

    function appConfig($routeProvider, $locationProvider) {
        $routeProvider
            .when('/login', resolve({
            templateUrl: '/content/views/login.htm',
            controller: 'loginCtrl'
        }))
            .when('/student/dashbroad', resolve({
            templateUrl: '/content/views/student-dashbroad.htm',
            controller: 'studentDashbroadCtrl'
        }))
            .when('/supervisor/dashbroad', resolve({
            templateUrl: '/content/views/supervisor-dashbroad.htm',
            controller: 'supervisorDashbroadCtrl'
        }))
            .when('/second-marker/dashbroad', resolve({
            templateUrl: '/content/views/second-marker-dashbroad.htm',
            controller: 'secondMarkerDashbroadCtrl'
        }))
            .when('/staff/dashbroad', resolve({
            templateUrl: '/content/views/second-marker-dashbroad.htm',
            controller: 'otherStaffDashbroadCtrl'
        }))
            .when('/student/message', resolve({
            templateUrl: '/content/views/message.htm',
            controller: 'msgCtrl'
        }))
            .when('/supervisor/message', resolve({
            templateUrl: '/content/views/message.htm',
            controller: 'msgCtrl'
        }))
            .when('/second-marker/message', resolve({
            templateUrl: '/content/views/message.htm',
            controller: 'msgCtrl'
        }))
            .when('/staff/message', resolve({
            templateUrl: '/content/views/message.htm',
            controller: 'msgCtrl'
        }))
            .when('/student/file', resolve({
            templateUrl: '/content/views/file.htm',
            controller: 'fileCtrl'
        }))
            .when('/supervisor/message', resolve({
            templateUrl: '/content/views/file.htm',
            controller: 'fileCtrl'
        }))
            .when('/second-marker/file', resolve({
            templateUrl: '/content/views/file.htm',
            controller: 'fileCtrl'
        }))
            .when('/staff/file', resolve({
            templateUrl: '/content/views/file.htm',
            controller: 'fileCtrl'
        }))
            .when('/student/meeting', resolve({
            templateUrl: '/content/views/meeting.htm',
            controller: 'meetingCtrl'
        }))
            .when('/supervisor/meeting', resolve({
            templateUrl: '/content/views/meeting.htm',
            controller: 'meetingCtrl'
        }))
            .when('/second-marker/meeting', resolve({
            templateUrl: '/content/views/meeting.htm',
            controller: 'meetingCtrl'
        }))
            .when('/staff/meeting', resolve({
            templateUrl: '/content/views/meeting.htm',
            controller: 'meetingCtrl'
        }))

            .when('/student/project', resolve({
            templateUrl: '/content/views/project.htm',
            controller: 'projectCtrl'
        }))
            .when('/supervisor/project', resolve({
            templateUrl: '/content/views/meeting.htm',
            controller: 'projectCtrl'
        }))
            .when('/second-marker/project', resolve({
            templateUrl: '/content/views/project.htm',
            controller: 'projectCtrl'
        }))
            .when('/staff/project', resolve({
            templateUrl: '/content/views/project.htm',
            controller: 'projectCtrl'
        }))
            .otherwise(resolve('/'));;

        function resolve(routeInfo, data?) {
            function beforeRun($q, $rootScope, $injector, $http, $location) {
                var defer = $q.defer();
                $http.get('/api/checklogin')
                    .success((res, status, headers, config) => {
                    if (res.userId === null && $location.path() !== '/login') {
                        document.location.href = '/login';
                    } else if (res.userId === null && $location.path() !== '/login') {
                        $rootScope.$emit('$rootScope:userLogged');
                    } else {
                        $rootScope.isLogin = true;
                        $rootScope.userId = res.userId;
                        $rootScope.userType = res.userType;
                        $rootScope.userName = res.userName;
                        defer.resolve();
                    }
                })
                    .error((res, status, headers, config) => {
                    defer.reject();
                });
                //var memberFactory = $injector.get('memberFactory');
                return defer.promise;
            }
            return {
                controller: routeInfo.controller,
                templateUrl: routeInfo.templateUrl,
                resolve: {
                    beforeRun: beforeRun
                }
            };
        }
        $locationProvider.html5Mode(true).hashPrefix('!');
    }
    appConfig['$inject'] = ['$routeProvider', '$locationProvider'];
    app.config(appConfig);

    function appRun($rootScope, $location, $http) {
        $rootScope.isLogin = false;

        $rootScope.redirect = (url) => {
            $location.path(url);
        };
        $rootScope.$on('$rootScope:noty',(event, mess, nType) => {
            var n = noty({
                layout: 'bottomRight',
                theme: 'bootstrapTheme',
                type: nType || 'success',
                text: mess, // can be html or string
                dismissQueue: true, // If you want to use queue feature set this true
                template: '<div class="noty_message"><span class="noty_text"></span><div class="noty_close"></div></div>',
                animation: {
                    open: { height: 'toggle' },
                    close: { height: 'toggle' },
                    easing: 'swing',
                    speed: 500 // opening & closing animation speed
                },
                timeout: 5000, // delay for closing event. Set false for sticky notifications
                force: false, // adds notification to the beginning of queue when set to true
                modal: false,
                maxVisible: 5, // you can set max visible notification for dismissQueue true option,
                killer: false, // for close all notifications before show
                closeWith: ['click', 'button'], // ['click', 'button', 'hover']
                buttons: false // an array of buttons
            });
        });
        $rootScope.$on('$rootScope:createPost',(event, model) => {
            model.to = model.to.userId;
            $http.post('/api/createpost', model).success((res, status, headers, config) => {
                var msg = '';
                if (res.Code !== 1) {
                    msg = 'Create new post fail.';
                } else {
                    msg = 'Create new post success.';
                }
                $rootScope.$emit('$rootScope:noty', msg);
            });
        });

        $rootScope.$on('$rootScope:pushComment',(event, model) => {
            $http.post('/api/pushcomment', model).success((res, status, headers, config) => {
                var msg = '';
                if (res.Code !== 1) {
                    msg = 'Send message fail.';
                } else {
                    msg = 'Message sent.';
                }
                $rootScope.$emit('$rootScope:noty', msg);
            });
        });

        //$rootScope.$on('$locationChangeStart',(event, next, current) => {
        //    var domain = 'http://' + $location.host();
        //    var port = $location.port();
        //    if (port !== 80) {
        //        domain += ':' + port;
        //    }
        //    domain += '/';
        //    if (domain !== next && !$rootScope.userId) {
        //        $rootScope.redirect('/');
        //    }
        //});
        $rootScope.$on('$rootScope:userLogged',() => {
            switch ($rootScope.userType) {
                case 1:
                    document.location.href = '/student/dashbroad';
                    break;
                case 2:
                    document.location.href = '/supervisor/dashbroad';
                    break;
                case 3:
                    document.location.href = '/second-marker/dashbroad';
                    break;
                case 4:
                    document.location.href = '/staff/dashbroad';
                    break;
            }
        });

        $rootScope.logout = () => {
            $http.get('/api/logout').success(() => {
                delete $rootScope.userType;
                delete $rootScope.userId;
                delete $rootScope.userName;
                delete $rootScope.currentProject;
                $rootScope.isLogin = false;
                document.location.href = '/login';
            });
        };

        $rootScope.refreshPeople = (item, peopleType) => {
            if (item === '') return;
            $http.get('/api/people', {
                params: { name: item, peopleType: peopleType }
            }).success((res) => {
                $rootScope.people = res.Data;
            });
        };

        $rootScope.refreshStudent = (item) => {
            if (item === '') return;
            $http.get('/api/people', {
                params: { name: item, peopleType: 1 }
            }).success((res) => {
                $rootScope.students = res.Data;
            });
        };

        $rootScope.refreshSupervisor = (item) => {
            if (item === '') return;
            $http.get('/api/people', {
                params: { name: item, peopleType: 2 }
            }).success((res) => {
                $rootScope.supervisors = res.Data;
            });
        };

        $rootScope.refreshSecondMarkers = (item) => {
            if (item === '') return;
            $http.get('/api/people', {
                params: { name: item, peopleType: 3 }
            }).success((res) => {
                $rootScope.secondMarkers = res.Data;
            });
        };

        $rootScope.refreshStaff = (item) => {
            if (item === '') return;
            $http.get('/api/people', {
                params: { name: item, peopleType: 4 }
            }).success((res) => {
                $rootScope.staffs = res.Data;
            });
        };
    }

    appRun['$inject'] = ['$rootScope', '$location', '$http'];
    app.run(appRun);

    function loginCtrl($rootScope, $scope, $http, $timeout) {
        $scope.login = () => {
            $http.post('/api/login', {
                user: $scope.user,
                pwd: $scope.pwd
            }).success((res, status, headers, config) => {
                if (res.Code !== 1) {
                    $rootScope.$emit('$rootScope:noty', 'User name or password is wrong.', 'warning');
                } else {
                    $rootScope.userType = res.Data.userType;
                    $rootScope.userId = res.Data.userId;
                    $rootScope.userName = res.Data.userName;
                    $rootScope.$emit('$rootScope:noty', 'Login success.', 'success');
                    $timeout(() => {
                        $rootScope.$emit('$rootScope:userLogged');
                    }, 1000, true);
                }
            }).error((data, status, headers, config) => {
            });
        };
    }
    loginCtrl['$inject'] = ['$rootScope', '$scope', '$http', '$timeout'];
    app.controller('loginCtrl', loginCtrl);

    function studentDashbroadCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Student dashbroad';

        $http.get('/api/Statistic')
            .success((res, status, headers, config) => {
            $scope.statistic = res;
        }).error((res, status, headers, config) => {
        });
    }
    studentDashbroadCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('studentDashbroadCtrl', studentDashbroadCtrl);

    function msgCtrl($rootScope, $scope, $http, $timeout) {
        $rootScope.pageName = 'Message';
        $scope.selectedItem = { toUser: { userId: '' } };

        $scope.send = () => {
            $rootScope.$emit('$rootScope:createPost', {
                to: $scope.selectedItem.toUser,
                content: $scope.content
            });
            $timeout(() => {
                $http.get('/api/getposts')
                    .success((res, status, headers, config) => {
                    $scope.messages = res;
                });
            }, 1000, true);

        };
        $scope.push = (message) => {
            message.comments.push(
                {
                    "from": {
                        "_id": $rootScope.userId,
                        "userName": $rootScope.userName,
                        "userType": $rootScope.userType
                    },
                    "content": message.newComment
                });
            $rootScope.$emit('$rootScope:pushComment', {
                msgId: message._id,
                content: message.newComment
            });
            message.newComment = '';
        };
        $http.get('/api/getposts')
            .success((res, status, headers, config) => {
            $scope.messages = res;
        });
    }
    msgCtrl['$inject'] = ['$rootScope', '$scope', '$http', '$timeout'];
    app.controller('msgCtrl', msgCtrl);

    function fileCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'File manager';
    }
    msgCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('fileCtrl', fileCtrl);

    function meetingCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Meeting';
    }
    meetingCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('meetingCtrl', meetingCtrl);

    function projectCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Project';
        $scope.saveProject = (project) => {
            if (project.selectedStudent)
                project.student = project.selectedStudent.userId;
            if (project.selectedSupervisor)
                project.supervisor = project.selectedSupervisor.userId;
            if (project.selectedSecondMarker)
                project.secondMarker = project.selectedSecondMarker.userId;
            $http.post('/api/saveproject', project).success((res, status, headers, config) => {
                $rootScope.$emit('$rootScope:noty', 'Update project success.', 'success');
                delete $scope.project;
                $http.get('/api/getprojects')
                    .success((res, status, headers, config) => {
                    $scope.projects = res;
                });
            }).error((data, status, headers, config) => {
            });
        };
        $scope.newProject = () => {
            $scope.project = {};
        };
        $scope.selectProject = (project) => {
            $scope.project = project;
        };
        $http.get('/api/getprojects')
            .success((res, status, headers, config) => {
            $scope.projects = res;
        });
    }
    projectCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('projectCtrl', projectCtrl);

    function supervisorDashbroadCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Supervisor dashbroad';
    };
    supervisorDashbroadCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('supervisorDashbroadCtrl', supervisorDashbroadCtrl);

    function secondMarkerDashbroadCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Second marker dashbroad';
        console.log('secondMarkerDashbroadCtrl');
    }
    secondMarkerDashbroadCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('secondMarkerDashbroadCtrl', secondMarkerDashbroadCtrl);

    function otherStaffDashbroadCtrl($rootScope, $scope, $http) {
        $rootScope.pageName = 'Other staff dashbroad';
        console.log('otherStaffDashbroadCtrl');
    }
    otherStaffDashbroadCtrl['$inject'] = ['$rootScope', '$scope', '$http'];
    app.controller('otherStaffDashbroadCtrl', otherStaffDashbroadCtrl);

    angular.bootstrap(document, ['app']);
});